<template>
  <div>
    <box t1="商品管理" t2="分类参数">
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <br>
      <el-row>
        <el-col>
          <span>选择商品分类：
            <el-cascader
              v-model="selectedCateKeys"
              :options="catesList"
              :props="selectCateProps"
              @change="handleCateChange"
              clearable
            ></el-cascader>
          </span>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParamsdialogVisible=true"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border="" stripe>
            <el-table-column type="expand">
              <!-- 参数选项 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="item.attr_id"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 可切换的标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="min"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="min"
                  icon="el-icon-delete"
                  @click="removeParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addParamsdialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border="" stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="item.attr_id"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 可切换的标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="min"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="min"
                  icon="el-icon-delete"
                  @click="removeParamsById(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </box>
    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+titleText"
      :visible.sync="editParamsdialogVisible"
      width="50%"
      @close="resetEditForm"
    >
      <el-form ref="editParamsForm" :model="editForm" label-width="80px" :rules="addParamsRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsdialogVisible"
      width="50%"
      @close="resetParamsForm"
    >
      <el-form ref="addParamsForm" :model="addForm" label-width="80px" :rules="addParamsRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      catesList: [],
      selectCateProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      selectedCateKeys: [],
      activeName: "many",
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      addParamsdialogVisible: false,
      addForm: {
        attr_name: ""
      },
      addParamsRules: {
        attr_name: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur"
          }
        ]
      },
      // 控制修改参数弹出框
      editParamsdialogVisible: false,
      editForm: {}
    };
  },
  methods: {
    //   获取商品分类数据
    async getCatesList() {
      const res = await this.$http.get("categories");
      if (res.meta.status != 200)
        return this.$message.error("获取商品分类数据失败");
      this.catesList = res.data;
    },
    handleCateChange() {
      if (this.selectedCateKeys.length != 3)
        return (this.selectedCateKeys = []);
      // (this.manyTableData = []),
      // (this.onlyTableData = [])

      this.getParamsData();
    },
    handleClick() {
      this.getParamsData();
    },
    // 获取分类下参数列表
    async getParamsData() {
      if (this.selectedCateKeys.length != 3) return;
      const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      });
      if (res.meta.status != 200)
        return this.$message.error("获取商品参数失败");

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        // 控制输入框和按钮的切换
        item.inputVisible = false;
        item.inputValue = "";
      });
      console.log(res.data);
      if (this.activeName == "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    resetParamsForm() {
      this.$refs.addParamsForm.resetFields();
    },
    addParams() {
      this.$refs.addParamsForm.validate(async valid => {
        if (!valid) return;
        const res = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status != 201) return this.$message.error("添加失败");

        this.$message.success("添加成功");
        this.getParamsData();
        this.addParamsdialogVisible = false;
      });
    },
    resetEditForm() {
      this.$refs.editParamsForm.resetFields();
    },
    editParams() {
      this.$refs.editParamsForm.validate(async valid => {
        if (!valid) return;
        const res = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editForm.attr_vals
          }
        );
        if (res.meta.status != 200) return this.$message.error("修改失败");
        this.$message.success("修改成功");
        this.getParamsData();
        this.editParamsdialogVisible = false;
      });
    },
    async showEditDialog(attr_id) {
      const res = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status != 200) return this.$message.error("获取参数失败");

      this.editParamsdialogVisible = true;
      this.editForm = res.data;
    },
    async removeParamsById(attr_id) {
      const isConfirm = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (isConfirm == "cancel") return this.$message.info("操作已取消");
      const res = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getParamsData();
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveAttrVals(row);
    },
    showInput(row) {
      row.inputVisible = true;
      // $nextTick的方法的作用就是当页面元素重新渲染时才会去执行回调函数
      // 数据改变比页面元素渲染快很多。因此需要$nextTick
      this.$nextTick(_ => {
        //  this.$refs.saveTagInput先拿到el-input组件
        // el-input.$refs.input获得dom元素
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveAttrVals(row);
    },
    async saveAttrVals(row) {
      const res = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status != 200) return this.$message.error("操作失败");
      this.$message.success("操作成功");
    }
  },
  created() {
    this.getCatesList();
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length == 3) return false;
      return true;
    },
    cateId() {
      if (this.selectedCateKeys.length == 3) return this.selectedCateKeys[2];
    },
    titleText() {
      if (this.activeName == "many") return "动态参数";
      return "静态属性";
    }
  },
  watch: {
    "selectedCateKeys.length": function(length) {
      if (length != 3)
        return (this.onlyTableData = []), (this.manyTableData = []);
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>